<?php
namespace app\api\controller;

class Bill extends Permission
{
    public function getList()
    {
        $page = isset($this->input_data['page']) ? $this->input_data['page'] : 1;
        $limit = isset($this->input_data['limit']) ? $this->input_data['limit'] : 15;
        $map = $this->_listMap();

        
        // 即将到期的列表
        $order = 'id DESC';
        if( $this->input_data['listType'] == '即将到期' )
        {
            $order = 'deadline ASC,id DESC';
            $currentDate = date('Y-m-d',strtotime('+1 days'));
            $futureDate = date('Y-m-d', strtotime('+30 days'));
            $map['deadline'] = ['BETWEEN',[$currentDate,$futureDate]];
        }
        // 已过期的列表
        if( $this->input_data['listType'] == '已过期' )
        {
            $order = 'deadline ASC,id DESC';
            $currentDate = date('Y-m-d',strtotime('+1 days'));
            $map['deadline'] = ['<',$currentDate];
        }


        $total = db('Bill')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->where($map)->count();
        $rows = db('Bill')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.company,b.plate_number,b.realname,b.tel')->order($order)->page($page,$limit)->where($map)->select();


        $list = $this->_formatData($rows);
        
        
        $data = [
            'total' => $total,
            'list' => $list
        ];
        $this->resSuc($data);
    }

    private function _formatData($rows)
    {
        $list = [];

        foreach ($rows as $v) {
            $v['grandfather'] = $v['grandfather'] == '' ? $v['realname'] : $v['grandfather'];
            $v['grandfather_tel'] = $v['grandfather_tel'] == '' ? $v['tel'] : $v['grandfather_tel'];
            $v['totalAmount'] = formatMoneyShow(bcadd($v['amount'],$v['interest']));
            $v['amount'] = formatMoneyShow($v['amount']);
            $v['interest'] = formatMoneyShow($v['interest']);
            $v['interest_rate'] = formatMoneyShow($v['interest_rate']);
            $v['repay_amount'] = formatMoneyShow($v['repay_amount']);
            $v['deduction_amount'] = $v['deduction_amount'] == 0 ? '无' : formatMoneyShow($v['deduction_amount']);
            $v['deadlineDay'] = timeToDay(strtotime($v['deadline']));
            $v['statusText'] = $v['repay_status'] == 1 ? '已还清' : '待还款';
            
            $list[] = $v;
        }
        return $list;
    }
    private function _listMap()
    {
        $map = [];
        if($this->post('area_id') != '')
        {
            $map['a.area_id'] = $this->post('area_id');
        }
        else
        {
            $ids = $this->myAllAreaIds;
            $ids[] = 0;
            $map['a.area_id'] = ['IN',$ids];
        }
        if( isset($this->input_data['company']) && $this->input_data['company'] != '') $map['b.company'] = ['LIKE','%'.$this->input_data['company'].'%'];
        if( isset($this->input_data['plate_number']) && $this->input_data['plate_number'] != '') $map['b.plate_number'] = ['LIKE','%'.$this->input_data['plate_number'].'%'];
        if( isset($this->input_data['grandfather']) && $this->input_data['grandfather'] != '') $map['a.grandfather'] = ['LIKE','%'.$this->input_data['grandfather'].'%'];

        if( isset($this->input_data['repay_status']) && $this->input_data['repay_status'] != '全部' ) $map['a.repay_status'] = $this->input_data['repay_status'];

        if( isset($this->input_data['cate']) && $this->input_data['cate'] != '全部' ) $map['a.cate'] = $this->input_data['cate'];

        
        return $map;
    }

    public function repay()
    {
        $this->_validRepay();
        $data = [
            'repay_type' => $this->input_data['type'],
            'vehicle_id' => $this->input_data['vehicle_id'],
            'bill_id' => $this->input_data['id'],
            'amount' => formatMoneySave($this->input_data['amount']),
            'pay_images' => $this->input_data['pay_images'],
            'pay_time' => strtotime($this->input_data['pay_time']),
            'bill_cate' => $this->input_data['bill_cate'],
            'create_user' => $this->user['realname'],
            'create_user_id' => $this->user['id'],
            'create_time' => time(),
        ];
        db('BillRepayRecord')->insert($data);

        $this->resSuc('ok');
    }

    // 还款审核
    public function judge()
    {
        $record = db('BillRepayRecord')->where(['id'=>$this->input_data['id']])->find();
        $record['status'] = $this->input_data['status'];
        $record['judge_user_id'] = $this->user['id'];
        $record['judge_user'] = $this->user['realname'];
        $record['judge_time'] = time();
        if($record['status'] == 200)
        {
            $record['pay_time'] = strtotime($this->input_data['pay_time']);
            $record['amount'] = formatMoneySave($this->input_data['amount']);
        }
        

        db('BillRepayRecord')->update($record);


        # 如果是审合通过，生成收支记录，还款到账单里面
        if($this->input_data['status'] == 200)
        {
            $plateNumber = db('Vehicle')->where(['id'=>$record['vehicle_id']])->value('plate_number');
            $amount = $record['amount'];
            # 保存还款记录
            $remark = '';
            $normalRepay = $record['bill_cate'] == '垫付' && $record['repay_type'] == '逾期费' ? false : true;
            if(!$normalRepay) $remark = '还逾期费';
            $data = [
                'cate' => '账单还款',
                'type' => '收入',
                'relation_id' => $record['id'],
                'relation_name' => $plateNumber ? $plateNumber : '',
                'amount' => $amount,
                'images' => $record['pay_images'],
                'pay_time' => $record['pay_time'],
                'remark' => $remark,
                'create_user' => $this->user['realname'],
                'create_user_id' => $this->user['id'],
                'create_time' => time()
            ];

            $repay_record_id = db('PayRecord')->insertGetId($data);

            # 把钱还到账单里面
            if($normalRepay) $this->_repayBill($record['bill_id'],$amount);

            # 更新账单信息
            $this->_updateBillRepay($record['bill_id']);

            # 提前还款 暂时不知道提前还款的逻辑
            // if($this->input_data['type'] == '提前还款') $this->_prepay($v);
        }   
        
        
        

        $this->resSuc('ok');
    }

    // 提前还款
    private function _prepay($billId)
    {
        $map = [
            'relation_id' => $billId,
            'cate' => '账单还款'
        ];
        $amount = db('PayRecord')->where($map)->sum('amount');
        $data = [
            'repay_amount' => $amount, //已还金额
            'prepay_images' => $this->input_data['prepay_images'],
            'repay_type' => $this->input_data['type'] == '正常' ? '' : $this->input_data['type'],
            'deduction_amount' => formatMoneySave($this->input_data['deduction_amount']),
            'repay_status' => 1
        ];

        db('Bill')->where(['id'=>$billId])->update($data);
    }

    // 还款数据验证
    private function _validRepay()
    {
        if($this->input_data['amount'] == 0) $this->resErr('还款金额不能为0');
        if($this->input_data['pay_images'] == '') $this->resEr('请上传付款凭证');

        // if($this->input_data['type'] == '提前还款')
        // {
        //     if($this->input_data['deduction_amount'] < 1 ) $this->resErr('减免金额不能为0');
        //     if($this->input_data['prepay_images'] == '') $this->resEr('请上传提前还款相关材料');
        // }
    }

    // 更新账单已还总数
    private function _updateBillRepay($billId)
    {
        $bill = db('Bill')->where(['id'=>$billId])->find();
        $totalAmount = bcadd($bill['amount'], $bill['interest']);
        $map = [
            'bill_id' => $billId,
            'status' => 200
        ];
        $repayAmount = db('BillRepayRecord')->where($map)->sum('amount');
        $map['repay_type'] = '正常';
        $repayBillAmount = db('BillRepayRecord')->where($map)->sum('amount');

        $data = [
            'repay_amount' => $repayAmount,
            'repay_status' => $totalAmount > $repayBillAmount ? 0 : 1,
        ];

        db('Bill')->where(['id'=>$billId])->update($data);
    }

    private function _repayBill($billId,$amount)
    {
        # 找未还清的账单
        $map = [
            'bill_id' => $billId,
            'repay_done' => 0
        ];
        $details = db('BillDetail')->where($map)->order('id ASC')->select();

        # 还进去
        foreach ($details as $v) {
            if( $amount < 1 ) break;
            // 当期账单剩余未还金额
            $sy = bcsub($v['amount_total'],$v['repay_total']);

            // 还的钱，大于本期金额
            // if($amount > $sy)
            // {
            //     $repayAmount = $sy; // 本期剩余金额
            // }
            // else
            // {
            //     // 先还到本金
            // }
            $repayAmount = $amount > $sy ? $sy : $amount;
            $v['repay_total'] += $repayAmount;
            $v['repay_done'] = $v['repay_total'] == $v['amount_total'] ? 1 : 0;
            db('BillDetail')->update($v);
            $amount -= $repayAmount;
        }
    }

    # 导出表格
    public function export()
    {
        $map = $this->_listMap();


        $rows = db('Bill')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number,b.realname,b.tel')->order('id DESC')->where($map)->select();
        $list = $this->_formatData($rows);
        $data = [
            'list' => $list,
            'type' => 'bill'
        ];
        $excelName = action('common/PhpOffice/exportExcel',$data);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$excelName;

        $this->resSuc($url);
    }
    # 导出表格
    public function exportExpired()
    {
        $map = $this->_listMap();


        $rows = db('Bill')->alias('a')->join('vehicle b','a.vehicle_id = b.id','LEFT')->field('a.*,b.area,b.company,b.plate_number,b.realname,b.tel')->order('id DESC')->where($map)->select();
        $list = $this->_formatData($rows);
        $data = [
            'list' => $list,
            'type' => 'bill'
        ];
        $excelName = action('common/PhpOffice/exportExcel',$data);
        $url = 'http://'.$_SERVER['HTTP_HOST'].'/'.$excelName;

        $this->resSuc($url);
    }

    // 账单录入
    public function update()
    {
        $amount = formatMoneySave($this->post('amount'));
        $data = [
            'area' => $this->post('area'),
            'area_id' => $this->post('area_id'),
            'vehicle_id' => $this->post('vehicle_id'),
            'amount' => $amount,
            'cate' => $this->post('cate'),
            'remark' => $this->post('remark'),
            'images' => $this->post('images'),
            'deadline' => $this->post('deadline'),
            'grandfather_tel' => $this->post('grandfather_tel'),
            'grandfather' => $this->post('grandfather'),
        ];

        $billId = db('Bill')->insertGetId($data);

        # 生成账单明细

        $data = [
            'bill_id' => $billId,
            'amount' => $amount,
            'interest' => 0,
            'deadline' => $this->post('deadline'),
            'times' => 0, 
        ];
        db('BillDetail')->insert($data);

        $this->resSuc('ok');
    }
  

}
